/*
    This is a set of libraries to assist in OpenGl and Other Applications
    Copyright (C) 2008  The Modular Engine Team

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#define ENGINECORE
#include "engineCore.h"

namespace ModularEngine
{
	EngineCore::EngineCore()
	{
		// sets things to the way they should be.
		mbRunning = false;
		mbInitialized = false;
	}

	int EngineCore::loadModule(ModularEngine::ModuleBase *module)
	{
		// Merely pushes the module back onto the module list.
		module->initialize();
		mlModuleList.push_back( module );
		return 1;
	}

	int EngineCore::init()
	{
#ifdef PORTING
		// Calls the initialize function of all the modules.
		for( std::list<ModuleBase *>::iterator i = mlModuleList.begin(); i != mlModuleList.end(); i++ )
		{
			if( !(*i)->initialize() )
			{
				THROWERROR( "Could Not Initialize All Modules." );
				return 0;
			}
		}
#endif
		mbInitialized = true; // It's true, we can move on.
		return 1;
	}

	void EngineCore::throwError( char *errorText, char *fileName, int lineNumber )
	{
		// Throws an error based on given info.
		std::cout << errorText << std::endl;
		std::cout << "FILE: " << fileName << std::endl;
		std::cout << "LINE: " << lineNumber << std::endl;
	}

	int EngineCore::run()
	{
		// Engine loop.  Continue running until told to stop.
		if( !mbInitialized )
		{
			THROWERROR( "Cannot Run.  Engine Not Initialized." );
			//throwError( "Cannot Run.  Engine Not Initialized.", __FILE__, __LINE__ );
			return 0;
		}

		// start running the engine then.
		mbRunning = true; 

		// While mbRunning is true, loop through the modules loaded and run them.
		while( mbRunning )
		{
			for( std::list<ModuleBase *>::iterator i=mlModuleList.begin(); i != mlModuleList.end(); i++ )
			{
				(*i)->run();
			}
		}
		return 1;
	}

	int EngineCore::stop()
	{
		// Stops the engine loop.  Will not return 0 unless already stopped.
		if( mbRunning )
		{
			mbRunning = false;
			return 1;
		}
		return 0;
	}

	bool EngineCore::status()
	{
		// If true, engine is running.  If false, its not.
		return mbRunning;
	}

	EngineCore::~EngineCore()
	{
		// Unloads all modules and cleans them up, or should.
	}
}
